package com.csw.shuanfa.utils.dateTime;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 节假日获取
 * 支持年头年尾顺延获取
 */
/**
 * 效果实例，
 * HolidayEntity(firstDay=20221231, lastDay=20230102, holidayDays=3)
 * HolidayEntity(firstDay=20230107, lastDay=20230108, holidayDays=2)
 * HolidayEntity(firstDay=20230114, lastDay=20230115, holidayDays=2)
 * HolidayEntity(firstDay=20230121, lastDay=20230127, holidayDays=7)
 * HolidayEntity(firstDay=20230204, lastDay=20230205, holidayDays=2)
 */
public class HolidayUtil2 {
    public static final String ZERO_0 = "0";
    public static final String ZERO_1 = "1";
    public static final String ZERO_2 = "2";

    public static void main(String[] args) throws ParseException {
         judgeDate();

//        // 创建一个Calendar对象
//        Calendar calendar = Calendar.getInstance();
//
//        // 设置日期为当年的1月1日
//        calendar.set(Calendar.MONTH, Calendar.JANUARY);
//        calendar.set(Calendar.DAY_OF_MONTH, 1);
//
//        // 遍历一年中的每一天
//        while (calendar.get(Calendar.YEAR) == 2023) {
//            int year = calendar.get(Calendar.YEAR);
//            int month = calendar.get(Calendar.MONTH) + 1;
//            int day = calendar.get(Calendar.DAY_OF_MONTH);
//
//            System.out.println(year + "-" + month + "-" + day);
//
//            // 增加一天
//            calendar.add(Calendar.DAY_OF_MONTH, 1);
//        }
    }

    /**
     * 判断今日是否为工作日
     *
     * @param httpArg
     * @return
     */
    public static String request(String httpArg) {
        String httpUrl = "http://tool.bitefu.net/jiari/";
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?d=" + httpArg;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static List judgeDate() throws ParseException {

        Calendar calendar = Calendar.getInstance();
        //指定年份测试用
        //calendar.set(Calendar.YEAR,2022);
        //设置为今年的1月1号
        // 设置日期为当年的1月1日
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.DAY_OF_MONTH, 1);

        int year = calendar.get(calendar.YEAR);
        String earlyDay = getEarlyDay(year);
        String lastedDay = getLastedDay(year);

        String earlyHoliday = "";
        String lastHoliday = "";
        List list = new ArrayList();
        while (calendar.get(Calendar.YEAR) == year) {

            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            String woringDays = getWoringDays(year, month + "", day + "");

            if (woringDays.equals("20231230")) {
                System.out.println("");
            }

            String jsonResult = HolidayUtil2.request(woringDays);
            if (woringDays.equals(earlyDay)) {
                if (ZERO_1.equals(jsonResult) || ZERO_2.equals(jsonResult)) {
                    //找出最早一天放假的节假日
                    earlyHoliday = getEarlyHokidayDay(woringDays);
                }
            }

            if (ZERO_1.equals(jsonResult) || ZERO_2.equals(jsonResult)) {
                if (StringUtils.isEmpty(earlyHoliday)) {
                    earlyHoliday = woringDays;
                }
                if (woringDays.equals(lastedDay)) {
                    if (ZERO_1.equals(jsonResult) || ZERO_2.equals(jsonResult)) {
                        //找出最晚一天放假的节假日
                        lastHoliday = getLastedHokidayDay(woringDays);
                        addHolidayEntity(earlyHoliday, lastHoliday, list);
                    }
                } else {
                    lastHoliday = woringDays;
                }
            } else {
                if (StringUtils.isNotEmpty(earlyHoliday)) {
                    addHolidayEntity(earlyHoliday, lastHoliday, list);
                }
                //清空
                earlyHoliday = "";

            }


            // 增加一天
            calendar.add(Calendar.DAY_OF_MONTH, 1);

            // 0 上班  1周末 2节假日
//            if (ZERO_0.equals(jsonResult)) {
//                woringDays = ZERO_0;
//            }
//            if (ZERO_1.equals(jsonResult)) {
//                woringDays = ZERO_1;
//
//            }
//            if (ZERO_2.equals(jsonResult)) {
//                woringDays = ZERO_2;
//            }
//            if (ZERO_0.equals(jsonResult)) {
//                System.out.println(woringDays + "上班");
//                //工作日");
///**
// * 判断当前时间是否在一个时间段内 HH:mm 格式
// */
//                String strStartTime1 = "00:00";
//                String strEndTime1 = "6:00";
//
//                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
//                String now = sdf.format(new Date());
//                Date nowTime;
//                try {
//                    nowTime = sdf.parse(now);
//                    Date startTime1 = sdf.parse(strStartTime1);
//                    Date endTime1 = sdf.parse(strEndTime1);
//                    // 注：也可以通过此方式判断当前时间是否具体时间段内 yyyy-MM-dd HH:mm:ss格式 [2022-03-09 12:00:00,2022-03-10 15:00:00]
//                    //   当前时间和时间段的格式保持一致即可判断
//                    if (isEffectiveDate(nowTime, startTime1, endTime1)) {
//                        System.out.println("在工作时间段内");
//                        //工作时间段");
//                    } else {//非工作时间段
//                        //非工作时间段");
//                        System.out.println("非工作时间段内");
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//            }
//            if (ZERO_1.equals(jsonResult)) {
//                woringDays = ZERO_1;
//                System.out.println(woringDays + "周末");
//            }
//            if (ZERO_2.equals(jsonResult)) {
//                woringDays = ZERO_2;
//                System.out.println(woringDays + "节假日");
//            }
        }
        for (int i = 0; i < list.size(); i++) {
            //插入数据库的时候先查询，不要重复插入
            System.out.println(list.get(i));

        }


        return list;
    }

    public static void addHolidayEntity(String earlyHoliday, String lastHoliday, List list) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date date = sdf.parse(earlyHoliday);
        Date date1 = sdf.parse(lastHoliday);
        long l = date1.getTime() - date.getTime();
        int xcDay = (int) (l / (24 * 60 * 60 * 1000)) + 1;
        HolidayEntity holidayEntity = new HolidayEntity(convertDateFormat(earlyHoliday, "yyyyMMdd", "yyyy/MM/dd"),
                convertDateFormat(lastHoliday, "yyyyMMdd", "yyyy/MM/dd"), xcDay);
        list.add(holidayEntity);
    }

    /**
     * 日期格式转换
     *
     * @param dateStr
     * @param currentFormat
     * @param newFormat
     * @return
     */
    public static String convertDateFormat(String dateStr, String currentFormat, String newFormat) {
        DateFormat currentDateFormat = new SimpleDateFormat(currentFormat);
        DateFormat newDateFormat = new SimpleDateFormat(newFormat);

        try {
            Date date = currentDateFormat.parse(dateStr);
            return newDateFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 确保传进来是放假的那一天
     * 传入某一天是放假的，找出他最早放假的那一天
     *
     * @param woringDays
     * @throws ParseException
     */
    public static String getEarlyHokidayDay(String holidayDays) throws ParseException {
        String beforeday = getBeforeDay(holidayDays);
        String jsonResult = HolidayUtil2.request(beforeday);
        if (ZERO_1.equals(jsonResult) || ZERO_2.equals(jsonResult)) {
            return getEarlyHokidayDay(beforeday);
        } else {
            return holidayDays;
        }
    }

    /**
     * 确保传进来是放假的那一天
     * 传入某一天是放假的，找出他最早放假的那一天
     *
     * @param woringDays
     * @throws ParseException
     */
    public static String getLastedHokidayDay(String holidayDays) throws ParseException {
        String afterDay = getAfterDay(holidayDays);
        String jsonResult = HolidayUtil2.request(afterDay);
        if (ZERO_1.equals(jsonResult) || ZERO_2.equals(jsonResult)) {
            return getLastedHokidayDay(afterDay);
        } else {
            return holidayDays;
        }
    }

    public static String getWoringDays(int year, String month, String day) {
        if (month.length() == 1) {
            month = "0" + month;
        }
        if (day.length() == 1) {
            day = "0" + day;
        }
//            SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
//            //获取当前时间，格式为yyyyMMdd
//            String woringDays = sf.format(new Date());
        String woringDays = year + month + day + "";
        //System.out.println(woringDays);
        return woringDays;
    }


    /**
     * 判断当前时间是否在[startTime, endTime]区间，注意三个参数的时间格式要一致
     *
     * @param nowTime
     * @param startTime
     * @param endTime
     * @return 在时间段内返回true，不在返回false
     */
    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        return date.after(begin) && date.before(end);
    }

    /**
     * 获取前一天
     *
     * @param nyr
     * @return
     * @throws ParseException
     */
    public static String getBeforeDay(String nyr) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date date = sdf.parse(nyr);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // 设置日期为2023年4月21日
        //calendar.set(year, month, day);
        // 将日期减去一天
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        String previousDay = sdf.format(calendar.getTime());
        //System.out.println(previousDay);
        // 输出结果
        return previousDay;
    }

    /**
     * 获取后一天
     *
     * @param nyr
     * @return
     * @throws ParseException
     */
    public static String getAfterDay(String nyr) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date date = sdf.parse(nyr);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // 设置日期为2023年4月21日
        //calendar.set(year, month, day);
        // 将日期减去一天
        calendar.add(Calendar.DAY_OF_MONTH, 1);

        String afterDay = sdf.format(calendar.getTime());
        //System.out.println(afterDay);
        // 输出结果
        return afterDay;
    }

    /**
     * 获取某一年最早一天
     *
     * @param yea
     * @return
     */
    public static String getEarlyDay(int yea) {

        Calendar cal = Calendar.getInstance();
        if (yea != 0) {
            //写了是指定，可以不写
            cal.set(Calendar.YEAR, yea);
        }
        int year = cal.get(cal.YEAR);

        // 获取最早的一天
        cal.set(Calendar.DAY_OF_YEAR, 1);
        int earliestDay = cal.get(Calendar.DAY_OF_MONTH);
        int earliestMonth = cal.get(Calendar.MONTH) + 1; // 月份从0开始，需要加1

        return getWoringDays(year, earliestMonth + "", earliestDay + "");


    }

    /**
     * 获取某一年最晚一天
     *
     * @param yea
     * @return
     */
    public static String getLastedDay(int yea) {
        Calendar cal = Calendar.getInstance();
        if (yea != 0) {
            //写了是指定，可以不写
            cal.set(Calendar.YEAR, yea);
        }

        int year = cal.get(cal.YEAR);

        // 获取最晚的一天
        cal.set(Calendar.DAY_OF_YEAR, cal.getActualMaximum(Calendar.DAY_OF_YEAR));
        int latestDay = cal.get(Calendar.DAY_OF_MONTH);
        int latestMonth = cal.get(Calendar.MONTH) + 1; // 月份从0开始，需要加1
        return getWoringDays(year, latestMonth + "", latestDay + "");
    }
}
